package com.xuanmiao.smsback.web.util;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author shenjiankang 2018/11/13 20:25
 */

/**
 * @author shenjiankang 2018/11/13 20:25
 */
@Slf4j
@Component
public class ExcelUtils<T extends BaseRowModel> {

    public void exportExcel(HttpServletResponse response, List<T> list, Class<T> clz, String filePrefixName) {
        ServletOutputStream out = null;
        ExcelWriter writer = null;
        try {
            if (CollectionUtils.isEmpty(list)) {
                return;
            }
            out = response.getOutputStream();
            writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, true);
            String fileName = new String((filePrefixName + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()))
                    .getBytes(), "UTF-8");
            Sheet sheet1;
            if (clz == null) {
                sheet1 = new Sheet(1, 0, list.get(0).getClass());
            } else {
                sheet1 = new Sheet(1, 0, clz);
            }
            sheet1.setSheetName("Sheet1");
            writer.write(list, sheet1);
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            if (out != null) {
                out.flush();
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            if (writer != null) {
                writer.finish();
            }
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }

    public void exportExcel(HttpServletResponse response, List<T> list, String filePrefixName) {
        exportExcel(response, list, null, filePrefixName);
    }
}